package com.xing.service.impl;

import com.xing.entity.UserDetail;
import com.xing.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2024/7/16 13:45
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetail userDetail = null;
        try {
            userDetail = userService.getUserDetailByUsername(username);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (userDetail == null) {
            log.warn("UserDetailService.loadUserByUsername:用户为空");
        }
        initUserData(userDetail);
        return userDetail;
    }

    private void initUserData(UserDetail userDetail) {
        if (userDetail == null) {
            return;
        }
        List<String> perms = new ArrayList<>();
        perms.add("admin");
        userDetail.getUser().setPower(perms);
    }
}
